package client.child.thread;

import java.io.IOException;
import java.io.ObjectOutputStream;

import qq.login.gui.BackMessage;
import qq.message.DataPackage;
import qq.message.DataPackage.MessageType;
import qq.panel.gui.simple.BackPackageMain;
import qq.panel.gui.simple.PanelSimpleGUI;
/**
 * client的子线程接管客户端的输出流
 * 让主线程管理输入流
 * @author ZHUAN4
 *
 */
public class ClientChildThread implements Runnable{

	private String name;
	private ObjectOutputStream oos;
    private PanelSimpleGUI psg; 

    
	public String getNaem() {
		return name;
	}


	public void setNaem(String naem) {
		this.name = naem;
	}


	public PanelSimpleGUI getPsg() {
		return psg;
	}


	public void setPsg(PanelSimpleGUI psg) {
		this.psg = psg;
	}


	/**
	 * @param oos
	 * @param psg
	 */
	public ClientChildThread(String name,ObjectOutputStream oos, PanelSimpleGUI psg) {
		super();
		this.name=name;
		this.oos = oos;
		this.psg = psg;
	}


	public void run() {
		// TODO Auto-generated method stub
		
		BackPackageMain buttonStaue=new BackPackageMain();
//		System.out.println("child thread run.....");
		while(true)
		{
			try {
				Thread.sleep(100);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			buttonStaue=psg.getBpm();
//			System.out.println(buttonStaue.getStatue());
			if(buttonStaue.getStatue()!=0) //使用完毕设回为0
			{
				try {
					handleSendMessage(buttonStaue);
					System.out.println("client has a action");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else 
				continue;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 客户端子程序中处理接受到的来自聊天面板的信息
	 * 将信息整合成包发送给服务器
	 * @param buttonStaue
	 * @throws IOException
	 */
	public void handleSendMessage(BackPackageMain buttonStaue) throws IOException
	{
		System.out.println("client get a message from main panel");
		DataPackage tempSend=new DataPackage();
		tempSend.setFromName(name);
		tempSend.setToName(buttonStaue.getToName());
		tempSend.setTime(System.currentTimeMillis());
		if(buttonStaue.getType()==3)
		{
			tempSend.setMessageData(buttonStaue.getMessage());
			tempSend.setMessageType(MessageType.SHAKE);
			System.out.println("send a shake");
		}
		else if(buttonStaue.getType()==4)
		{
			tempSend.setMessageData(buttonStaue.getMessage());
			tempSend.setMessageType(MessageType.LOGOUT);
			System.out.println("send a logout");
		}
		else
		{
			tempSend.setMessageData(buttonStaue.getMessage());
			tempSend.setMessageType(MessageType.MESSAGE);
			System.out.println("send a message");
		}
		oos.writeObject(tempSend);	
		System.out.println("client send a message");
		psg.getBpm().setStatue(0);
	}
	
	
}
